﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace MultipleTasks
{
    public sealed partial class MultipleTasksFlow : SequentialWorkflowActivity
    {
        public MultipleTasksFlow()
        {
            InitializeComponent();
        }
        string mainList = "Test1";
        public Guid workflowId = default(System.Guid);
        private int curTaskID = 0;
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
        public IList assignees = default(System.Collections.IList);
        private string workflowName = "rf";
        private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
        {
            workflowId = workflowProperties.WorkflowId;
        }



        private void replicateTasks_Initialized(object sender, EventArgs e)
        {
            this.spTaskActivity1.IsParallelTask = false;
            this.spTaskActivity1.SPTaskProperties.ExtendedProperties.Add("Url", this.workflowProperties.SiteUrl);
            this.spTaskActivity1.SPTaskProperties.ExtendedProperties.Add("List", mainList);
            this.spTaskActivity1.SPTaskProperties.ExtendedProperties.Add("Itemid", this.workflowProperties.ItemId);
            this.spTaskActivity1.SPTaskProperties.ExtendedProperties.Add("Wfname", "rf");
            this.spTaskActivity1.SPTaskProperties.ExtendedProperties.Add("ApprovalLevel", this.workflowProperties.Item["ApprovalLevel"].ToString());

        
            //Create a set of assignees for taska
            assignees = new ArrayList();
            if (!string.IsNullOrEmpty(this.workflowProperties.InitiationData)
                && !this.workflowProperties.InitiationData.Contains('<'))
            {

                if (this.workflowProperties.InitiationData.Contains(':'))
                {
                    if (this.workflowProperties.InitiationData.Split(':')[0].Equals("Parallel", StringComparison.CurrentCultureIgnoreCase))
                    {
                        this.spTaskActivity1.IsParallelTask = true;
                    }
                    string[] userLogins = this.workflowProperties.InitiationData.Split(':')[1].Split(';');
                    foreach (var item in userLogins)
                    {
                        assignees.Add(item);
                    }
                    assignees.Add(userLogins[0]);
                }
            }
            else
            {
                if (workflowProperties.Item["ApprovalType"] != null &&
                    workflowProperties.Item["ApprovalType"].ToString().Equals("Parallel", StringComparison.CurrentCultureIgnoreCase))
                {
                    this.spTaskActivity1.IsParallelTask = true;
                }
                string[] uids = workflowProperties.Item["Reviews"].ToString().Split(';');

                for (int i = 0; i < uids.Length; i++)
                    assignees.Add(uids[i]);
                assignees.Add(uids[0]);
            }


            assignees.RemoveAt(0);
            //Set data for first task
            //  SPUser employee = GetUserFromPickerString(workflowProperties.Item["Employee"].ToString());
            spTaskActivity1.TaskAssignedTo = assignees[assignees.Count - 1].ToString();
            spTaskActivity1.TaskTitle = "WF Initialised Task: " + this.workflowProperties.Item["Title"].ToString();
            spTaskActivity1.TaskDescription = "Approve Vacation Request for " + spTaskActivity1.TaskAssignedTo + "WFId=" + workflowId;
            spTaskActivity1.TaskDueDate = DateTime.Today.AddDays(7);
           
        }

        private void replicateTasks_ChildInitialized(object sender, ReplicatorChildEventArgs e)
        {
            //Looping through each assignee
            //SPUser employee = GetUserFromPickerString(workflowProperties.Item["Employee"].ToString());
            spTaskActivity1.TaskAssignedTo = e.InstanceData.ToString();
            spTaskActivity1.TaskTitle = "WF Replicator Task: " + this.workflowProperties.Item["Title"].ToString();
            spTaskActivity1.TaskDescription = "1.Approve Vacation Request for " + spTaskActivity1.TaskAssignedTo + "WFId=" + workflowId;
            spTaskActivity1.TaskDueDate = DateTime.Today.AddDays(7);
        }


        private SPUser GetUserFromPickerString(string PickerString)
        {
            string id = string.Empty;
            try
            {
                id = PickerString.Substring(0, PickerString.IndexOf(';'));
                return workflowProperties.Web.SiteUsers.GetByID(int.Parse(id));
            }
            catch { return null; }

        }

        private void OnAllChildTaskCompleted(object sender, EventArgs e)
        {
            SPUtility.WorkflowHelper wfHlp = new SPUtility.WorkflowHelper();
            //SPUtility.LogHandler.LogError(SPUtility.LogType.Workflow, "Parallel task is About to cancel the workflow");

            wfHlp.ApproveWFProcess(
                    this.workflowProperties.SiteUrl,
                    mainList,
                    "ChildID",
                    this.workflowProperties.ItemId.ToString(),
                    workflowName, workflowProperties.Item["ApprovalLevel"].ToString(), Guid.Empty);
        }


    }
}
